<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;


use app\models\CtiConfig;
use app\models\CtiFile;
use common\helps\Tools;
use common\helps\UploadFiles;
use yii\helpers\ArrayHelper;

class CtiManagerIvrTuController  extends CtiManagerController
{

    /**
     * 导入ivr文件的内容
     */
    public $myfile = "";
    public function actionUpload()
    {
        try{
            $model = new CtiFile();
            $file = $_FILES['file'];
            $type = isset($_POST['type'])?$_POST['type']:"cti_ivr_tu";//设置上传的文件类型，如果不设置就是ivr文件
            //现在解析文件，内容解析成数组数据
            if (!empty($file)) {
                $count = CtiFile::find()->select("*")->where(["name"=>$file['name']])->count();
                $model->name = $file['name'];
                if ($count>0){//所上传的文件已经上传过了，
                    if($type == "cti_ivr_tu"){
                        return "1";
                    }else{
                        $one = CtiFile::findOne($_POST['id']);
                        $params_ = json_decode($_POST['params'],true);
                        $params_[1]['state'] = "yes";
                        $params['fileData'] = array_values($params_);
                        $one->updateAttributes(['params'=>json_encode($params)]);
                        $data['fileData'] = $params;
                        $data['res'] = "true";
                        $data['id'] = $_POST['id'];
                        return json_encode($data);
                    }
                }
                $fileData = $this->actionParseIvrFile($file['tmp_name']);
                $this->myfile = UploadFiles::common_upload_single($file);
                if(!empty($model->name) && $this->myfile){
                    //开启事务
                    $connection = \Yii::$app->getDb();
                    $transaction = $connection->beginTransaction();
                    $model->type = $type;
                    $model->path = $this->https_url.$this->myfile['filename'];
                    $model->filesize = $file['size'];
                    $model->create_at = time();
                    $data['fileData'] = $fileData;
                    $model->params = json_encode($data);
                    $model->save();
                    //更新导入了几条记录
                    $model->updateAttributes(['number'=>1]);
                    $transaction->commit();
                    //事务完成，一次性提交
                }
                $data['fileData'] = $fileData;
                $data['res'] = "true";
                $data['id'] = $model->attributes['id'];
                return json_encode($data);
            }else{
                return "false";
            }
        }catch (\Exception $e){
            Tools::l($e);
        }
    }

    public function actionUpdate(){
        $data = $_POST['data'];
        $model = CtiFile::findOne($_POST['id']);
        return $model->updateAttributes(['params'=>json_encode($data)]);
    }

    public function actionFindAllWav(){
        $ids = $_POST['params'];//拿到id
        $all = \Yii::$app->db->createCommand("select * from cti_file where id in ($ids)")->queryAll();//将所有的文件查询出来
        $data['data'] = $all;
        $data['res'] = "true";
        return json_encode($data);
    }


    /**
     * 导入语音文件到freeswitch
     */
    public function actionUploadFs()
    {
        try{
            $res = $this->actionUpload();
            if($res=="true"){//上传到本地成功
                // 现在上传到freeswitch
                $dest = str_replace("/","\\",$this->path.$this->fs_wav_path.'ivr\\8000\\'.$_FILES['file']['name']);
                $ress = copy("./".$this->myfile['filename'],$dest);
                if ($ress){
                    $path['path'] = 'ivr/'.$_FILES['file']['name'];
                    $path['src'] = $this->https_url.$this->myfile['filename'];
                    return json_encode($path);
                }else{
                    return false;
                }
            }else{
                return $res;
            }
        }catch (\Exception $e){
            Tools::l($e);
        }
    }

    /**
     * 保存数据
     */
    public function actionSave(){
        $xml = Tools::arrtoxml($_POST['data']);//将数组转化为xml数据
        //将conf/auto_configs/callcenter.conf.xml配置文件里面的内容替换掉，打开ivr
        $file = $this->path.'conf\\dialplan\\default.xml';
        if ($xml->menu['show-ivr']=="hidden"){//如果开关关闭了就表明关闭ivr
            $search = ['extension name="IMSGatewayInbound"','action','application="ivr"','data="my_in_ivr"'];
            $replace = ['extension name="IMSGatewayInbound"','action','application="ivr"','data=""'];
        }else{//开启ivr
            $search = ['extension name="IMSGatewayInbound"','action','application="ivr"','data=""'];
            $replace = ['extension name="IMSGatewayInbound"','action','application="ivr"','data="my_in_ivr"'];
        }
        $res = $this->replaceXmlFileConfig($file,$search,$replace,true);
        if ($res){
            $res2 = file_put_contents($file,$res);//替换掉服务器里面的文件内容
            if(!$res2){
                return false;
            }
        }
        $xmlContents = $xml->asXML();
        $xmlContents = str_replace(">",">\n",$xmlContents);//让文件实现换行，好读懂
        $res1 = file_put_contents($this->path.'conf\\ivr_menus\\my_in_ivr.xml',$xmlContents);//替换掉freeswitch里面的文件内容
        $https_url = $this->https_url;
        $temp = strpos($_POST['path'],$https_url);
        $res2 = file_put_contents(substr($_POST['path'],strlen($https_url)+$temp,strlen($_POST['path'])-strlen($https_url)),$xmlContents);//替换掉服务器里面的文件内容
        if ($res1>0&&$res2>0){
            $this->execFSBgapi("reloadxml");
            return true;
        }else{
            return false;
        }
    }

    /**
     * 解析ivr文件,内容解析成数组数据
     */
    public function actionParseIvrFile($file){
        $file_contents = file_get_contents($file);
        $file_contents = mb_convert_encoding($file_contents, 'UTF-8', 'GB2312');
        $file_contents_arr = explode("end",$file_contents);
        $final_res = '';
        foreach ($file_contents_arr as $k=>$v){
            $temp = explode("\r\n",$v);
            foreach ($temp as $kk=>$vv){
                $explode_si = explode("=",$vv);
                if (count($explode_si)>2){
                    $final_res[$k][trim($explode_si[0])] = $explode_si[1]."=".$explode_si[2];
                }elseif (count($explode_si)>1){
                    $final_res[$k][trim($explode_si[0])] = $explode_si[1];
                }else{
                    $explode_step = explode("[",$vv);
                    if (count($explode_step)>1){
                        $final_res[$k][trim($explode_step[0])] = substr($explode_step[1],0,strlen($explode_step[1])-1);
                    }
                }
            }
        }
//        $var = serialize($final_res);//将解析完成的ivr文件序列化
////        $res =  preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$var);
////        $res = unserialize($res);
        $ress = $this->actionParseTu($final_res);
        $tmp = mb_convert_encoding($ress, 'GBK', 'UTF-8');
        $this->ftpSaveFile(ArrayHelper::toArray($this->remark),'/scripts/my_in_ivr.lua',$tmp);
        $ressArr = explode("--<",$ress);
        $ressArr = array_filter($ressArr,function($var){
            return strpos($var,"js端需要上传的文件")!==false;
        });
        $finalRes = [];
        if (count($ressArr)>0){
            foreach ($ressArr as $k=>$v){
                $v = str_replace('/','\\',$v);
                $temp = explode("=",$v);
                $finalRes[$k]['filepath'] = $temp[1];
                $finalRes[$k]['state'] = "no";
            }
        }
        return $finalRes;
    }

    public $comd = "";//命令
    public function actionParseTu($res){
        if ($res){
            $this->comd = "";
            $this->comd .= "local dbh = freeswitch.Dbh(\"mysql:root:root\")";
            $this->comd .= "
assert(dbh:connected())";
            $this->comd .='
api = freeswitch.API()
session:set_tts_params(\'tts_commandline\', \'Ting-Ting\')
';
            $this->comd .='function searchOne(sql_query)
    local function set_session_variables(row)
      for key, val in pairs(row) do
        if session then
          session:setVariable(key, val)
        end
      end
    end
    dbh:query(sql_query, set_session_variables)
end
';//连接数据库并且查询
            $this->comd .= 'function split( str,reps )
    local resultStrList = {}
    string.gsub(str,"[^"..reps.."]+",function ( w )
        table.insert(resultStrList,w)
    end)
    return resultStrList
end
';//切割字符串
            $this->comd .= 'function tonumber(datestr)
    local dateend = split(datestr, ":");
    local day = "01";
    local month = "01";
    local year = "2018";
    local hour = dateend[1];
    local minute = dateend[2];
    local second = dateend[3];
    return os.time({day = day, month = month, year = year, hour = hour, minute = minute, second = second});
end
';//切割字符串
            $this->comd .= 'res = {}
function execute(sql_query)
    local function set_session_variables(row)
        for key, val in pairs(row) do
         res = val
      end
    end
    dbh:query(sql_query, set_session_variables)
end
';//切割字符串
            $this->comd .= '--可以将json字符串转化为数组，因为暂时window版本的cjson无法使用，还需要编译，麻烦，于是就这样写了
function parseJson( str,reps,reps2)
    local m = string.len(str)
    str = string.sub(str, 2, m-1)
    local resultStrList = {}
    string.gsub(str,"[^"..reps.."]+",function (w)
        local resultStrListTemp = {}
        string.gsub(w,"[^"..reps2.."]+",function (w_)
            table.insert(resultStrListTemp, w_)
        end)
        res = \'\'
        for key, val in pairs(resultStrListTemp) do
            if(key~=1) then
                res = res..\':\'..val
            end
        end
        local m_ = string.len(res)
        resultStrList[resultStrListTemp[1]] = string.gsub(string.sub(res, 2, m_), "\\\", "")
    end)
    return resultStrList
end
';//将json字符串转化为数组，因为暂时window版本的cjson无法使用，还需要编译，麻烦，于是就这样写了
            $this->comd .= "if (session:ready() == true) then\r\n";
            $temp = "";
            foreach ($res as $k=>$v){
                foreach ($v as $kk=>$vv){
                    $temp[$k][$kk] = array_filter(explode("/",$vv),"backend\controllers\CtiManagerIvrTuController::notEmpty");//下一步
                }
            }
            $this->actionConvertTuToLua($temp);
            $this->comd .= "end\r\n";
            return $this->comd;
        }
    }

    public $PriorStep;
    //将流程图解析完成的对象转化为lua语言，freeswitch可以识别的
    public function actionConvertTuToLua($temp){
        //这里拿到处理后的数据，每个切割成了数组 $temp=[NextStep=>[0=>"1",...],...]
        $arr1 = array_column ($temp,'step');
        array_multisort($arr1,SORT_ASC,$temp );
        foreach ($temp as $kk=>$vv) {//$kk1为NextStep，$vv1 为 [0=>"1",...]
            $this->comd .= "\t"."function step".$vv['step'][0]."()"."\r\n";
            $this->PriorStep = $temp[$vv['PriorStep'][0]<0?0:$vv['PriorStep'][0]];
            $this->comd .= $this->judgeAndCombine($kk,$vv);
            //以下为公共的代码以及逻辑
            $this->comd .= "\t"."end"."\r\n";
        }
        $this->comd .= "\t"."step0()"."\r\n";
    }

    /**
     * 合成包含逻辑的语句
     * @param $v 判断的条件
     * @param $command 判断的参数
     */
    public function judgeAndCombine($k,$v){
        try{
            $command = "";
            $step = $v['step'];
            $StepType = $v['StepType'];
            $Left = $v['Left'];
            $Top = $v['Top'];
            $subCaption = $v['subCaption'];
            $PriorStep = $v['PriorStep'];
            $Line1 = $v['Line1'];
            $Line2 = $v['Line2'];
            $Line3 = $v['Line3'];
            $Line4 = $v['Line4'];
            $Line5 = $v['Line5'];
            $NextStep = $v['NextStep'];
            $BeginLinePoint = $v['BeginLinePoint'];
            $EndLinePoint = $v['EndLinePoint'];
            $Memo = $v['Memo'];
            //这个是每个类型自己单独的代码逻辑
            switch ($StepType[0]){
                case "1"://开始
                    break;
                case "2"://语音
                    if (isset($Line1[0])){
                        if ($Line1[0]=="1"){//语音文件
                            $filepath = str_replace('\\','/',$Line2[0]);//文件路径
                            $basename = pathinfo($filepath)['basename'];//文件路径
                            $this->add("session:execute('playback', 'ivr/$basename')");//播放录音文件
                            $this->add("--<js端需要上传的文件=$filepath"."--<");//播放录音文件
                        }
                        if ($Line1[0]=="2"){//TTS
                            $this->add("session:answer()");
                            $this->add("session:sleep(100)");
                            $this->add("session:speak('$Line2[0]')");
                        }
                        if ($Line1[0]=="3"){//报工号
                        }
                        if ($Line1[0]=="4"){//别名放音
                        }
                        if ($Line1[0]=="4"){//问候语
                        }
                        if ($Line1[0]=="4"){//报队列
                        }
                    }
                    break;
                case "3"://按键
                    if (isset($Line1[0])){
                        if ($Line1[0]=="1"){//键值
                            $this->add("session:sleep(3000)");
                            $this->add("local digits = session:getDigits(1, \"\", 3000)");
                            foreach ($Line2 as $k=>$v){
                                $this->add("if '$v'==digits then");
                                $this->add("step".$NextStep[$k]."()",3);//跳转
                                $this->add("end");
                            }
                        }
                        if ($Line1[0]=="2"){//长度
                        }
                        if ($Line1[0]=="3"){//两者
                        }
                    }
                    break;
                case "4"://判断
                    if ($Line1[0]=="1"){//判断
                    }
                    if ($Line1[0]=="2"){//写入
                    }
                    if ($Line1[0]=="3"){//参数
                    }
                    if ($Line1[0]=="4"){//获取数据
                    }
                    if ((strpos($Line4[0],"CheckTime")!==false)){//检测时间过滤
                        $time = explode("=",$Line4[0]);//
                        if (count($time)>1){
                            $times = array_filter(explode(",",$time[1]));
                            $this->judgeJump("tonumber('$times[0]') > tonumber(os.date('%H:%M:%S')) or  tonumber(os.date('%H:%M:%S')) > tonumber('$times[1]')",$v['NextStep'][0]);
                            $this->judgeJump("tonumber('$times[0]') < tonumber(os.date('%H:%M:%S')) and  tonumber(os.date('%H:%M:%S')) < tonumber('$times[1]')",$v['NextStep'][1]);
                        }
                    }
                    if ((strpos($Line4[0],"TrunCallerByPhone")!==false)){//检测  电话号码 过滤是不是拨打我方的电话号码 为 这个号码argv[1]
                        $phone = explode("=",$Line4[0]);
                        if (count($phone)>=1){
                            //来的电话过滤，我们这边的座机不存在
                            $this->judgeJump("'$phone[1]' ~= argv[1]",$v['NextStep'][0]);
                            //来的电话过滤，我们这边的座机存在
                            $this->judgeJump("'$phone[1]' == argv[1]",$v['NextStep'][1]);
                        }
                    }
                    break;
                case "5"://坐席
                    if ((strpos($Line4[0],"TechGroup")!==false)){//检测  技能组
                        $techGroup = explode("=",$Line4[0]);
                        if (count($techGroup)>=1){//表示技能组有内容，就实现技能组
                            if ($Line4[3]=="1"){//关闭技能组

                            }else if ($Line4[1]=="1"){//开启技能组
                                $this->add("searchOne('select * from cti_jnz where name=\"$techGroup[1]\"')");//查询技能组数据
                                $this->add("local skill_level = session.getVariable(session,'skill_level')");//拿到技能等级
                                $this->add("local status = api:executeString(\"callcenter_config tier list\")");//拿到所有用户的列表
                                $this->add("local res = split(status,\"\\n\")");//将所有的用户列表切割成数组
                                $this->add("for i=2,#res-1 do");//对用户列表进行循环,第一个最后一个过滤掉
                                $this->add("local itemArr = split(res[i],\"|\")",3);//将单个的用户列表切割得到单个参数
                                $this->add("api:executeString(\"callcenter_config tier set level \"..itemArr[1]..\" \"..itemArr[2]..\" \"..skill_level)",3);//将所有的数据设置进去
                                $this->add("end",2);//for循环结束
                            }
                        }
                    }
                    if ($Line1[0]=="1"){//根据ACD自动分配
                        $this->add("local allCount = api:executeString(\"callcenter_config queue count agents support@default 'Available'\");");//自动分配坐席
                        $this->add("local availableCount = api:executeString(\"callcenter_config queue count agents support@default 'Available' 'Waiting'\");");//自动分配坐席
                        $this->add("if availableCount~='0\\n' then");//找到坐席
                        $this->add("step$NextStep[0]()",3);
                        $this->add("end");//结束
                        $this->add("if availableCount=='0\\n' then");//无坐席
                        $this->add("step$NextStep[1]()",3);
                        $this->add("end");//结束
                    }
                    if ($Line1[0]=="2"){//根据分机号分配
                        $this->add("local status = api:executeString(\" callcenter_config agent get status $Line2[0]@\${domain} \");");//自动分配坐席
                        $this->add("local state = api:executeString(\" callcenter_config agent get state $Line2[0]@\${domain} \");");//自动分配坐席
                        $this->add("if status=='Available' and state=='Waiting' then");//找到坐席
                        $this->add("step$NextStep[0]()",3);
                        $this->add("end");
                        $this->add("if status~='Available' or state~='Waiting' then");//无坐席
                        $this->add("step$NextStep[1]()",3);
                        $this->add("end");//结束
                    }
                    if ($Line1[0]=="3"){//根据号码归属地分配
                    }
                    if ($Line1[0]=="4"){//根据返回坐席分配
                    }
                    break;
                case "6"://录音
                    if (isset($Line1[0])){
                        if ($Line1[0]=="1"){//开始录音
                            if (isset($Line2[0])){
                                $ctiConfig = new CtiConfig();
                                $res = $ctiConfig->find()->where(['parent_type'=>'rdhpz'])->one();
                                $remark = json_decode($res->remark);
                                $httpPath = $remark->root.'/'.$remark->recordPath;
                                if ($Line2[0]=="1"){//压控
                                    $this->add("path = '/\${strftime(%Y-%m-%d)}/\${destination_number}/\${caller_id_number}_\${strftime(%H-%M-%S)}.wav'");
                                    $this->add("session:execute('set','path'..argv[1]..'='..path)");
                                    $this->add("path = session:getVariable('path'..argv[1])");
                                    $this->add("session:execute('set','caller_id_number=\${caller_id_number}')");
                                    $this->add("session:execute('set','destination_number=\${destination_number}')");
                                    $this->add("caller_id_number = session:getVariable('caller_id_number')");
                                    $this->add("destination_number = session:getVariable('destination_number')");
                                    $this->add("searchOne('select * from cti_config where type=\'rdhpz_freeswitchDirectory\'')");
                                    $this->add("remark = session:getVariable('remark')");
                                    $this->add("remarks = parseJson(remark,',','\\\":\\\"')");
                                    $this->add("absPath = '/'..remarks['recordPath']..path");
                                    $this->add("httpPath = remarks['root']..'/'..remarks['recordPath']..path");
                                    //将文件路径保存到数据库
                                    $this->add("execute('insert into cti_cdr_wav (`from`,`to`,`absPath`,`httpPath`,`createTime`,`uuid`) values (\"'..caller_id_number..'\",\"'..destination_number..'\",\"'..absPath..'\",\"'..httpPath..'\",\"'..os.time()..'\",\"'..session.uuid..'\")')");
                                    $this->add("session:execute('record_session',absPath)");//跳转
                                    $this->add("session:execute('export','dialed_extension=$1')");//跳转
                                }
                                if ($Line2[0]=="2"){//码控
                                    if (isset($Line4[0])){
                                        $this->add("session:sleep(1000)");
                                        $this->add("local digits = session:getDigits(1, \"\", 3000)");
                                        $this->add("if '$Line4[0]'==digits then");
                                        $this->add("path = '/\${strftime(%Y-%m-%d)}/\${destination_number}/\${caller_id_number}_\${strftime(%H-%M-%S)}.wav'");
                                        $this->add("session:execute('set','caller_id_number=\${caller_id_number}')");
                                        $this->add("session:execute('set','destination_number=\${destination_number}')");
                                        $this->add("caller_id_number = session:getVariable('caller_id_number')");
                                        $this->add("destination_number = session:getVariable('destination_number')");
                                        $this->add("session:execute('set','path'..argv[1]..'='..path)");
                                        $this->add("path = session:getVariable('path'..argv[1])");
                                        $this->add("searchOne('select * from cti_config where type=\'rdhpz_freeswitchDirectory\'')");
                                        $this->add("remark = session:getVariable('remark')");
                                        $this->add("remarks = parseJson(remark,',','\\\":\\\"')");
                                        $this->add("absPath = '/'..remarks['recordPath']..path");
                                        $this->add("httpPath = remarks['root']..'/'..remarks['recordPath']..path");
                                        //将文件路径保存到数据库
                                        $this->add("execute('insert into cti_cdr_wav (`from`,`to`,`absPath`,`httpPath`,`createTime`,`uuid`) values (\"'..caller_id_number..'\",\"'..destination_number..'\",\"'..absPath..'\",\"'..httpPath..'\",\"'..os.time()..'\",\"'..session.uuid..'\")')");
                                        $this->add("session:execute('record_session',absPath)");//跳转
                                        $this->add("session:execute('export','dialed_extension=$1')",3);//跳转
                                        $this->add("end");
                                    }
                                }
                            }
                        }
                        if ($Line1[0]=="2"){//停止录音
                        }
                    }
                    break;
                case "7"://留言
                    break;
                case "8"://传真
                    break;
                case "9"://打印
                    break;
                case "10"://结束
                    if (isset($Memo[0])){
                        $this->add("session:answer()");//无坐席
                        $this->add("session:sleep(100)");
                        $this->add("session:speak('$Memo[0]')");//无坐席
                    }
                    break;
                case "11"://挂机
                    break;
                case "12"://通话
                    if (isset($this->PriorStep['Line1'][0])){
                        if ($this->PriorStep['Line1'][0]=="1"){//上一步是否是ACD自动分配
                            $this->add("session:execute('callcenter','support@default')");//自动分配坐席
                        }
                        if ($this->PriorStep['Line1'][0]=="2"){//上一步是否是根据分机号分配
                            if (isset($Line1[0])){
                                $this->add("session:execute('bridge','sofia/internal/$Line1[0]%\${sip_profile}')");
                            }
                        }
                        if ($this->PriorStep['Line1'][0]=="3"){//上一步是否是根据号码归属地分配
                        }
                        if ($this->PriorStep['Line1'][0]=="4"){//上一步是否是根据返回坐席分配
                        }
                    }
                    break;
                case "13"://队列
                    break;
                case "14"://摘机
                    break;
                case "15"://拨号
                    $this->add("session:execute('bridge',\"sofia/gateway/gw\"..argv[1]..\"/0$Line1[0]\")");//拨号的电话号码
                    $this->add("local bridge_hangup_cause = session:getVariable(\"bridge_hangup_cause\") or session:getVariable(\"originate_disposition\");");//拨号的电话号码
                    $this->add("if bridge_hangup_cause=='NORMAL_CLEARING' then");
                    $this->add("step".$NextStep[0]."()",3);//跳转
                    $this->add("end");
                    $this->add("if bridge_hangup_cause=='USER_BUSY' then");
                    $this->add("step".$NextStep[1]."()",3);//跳转
                    $this->add("end");
                    $this->add("if bridge_hangup_cause=='NO_USER_RESPONSE' then");
                    $this->add("step".$NextStep[2]."()",3);//跳转
                    $this->add("else");
                    $this->add("step".$NextStep[3]."()",3);
                    $this->add("end");
                    break;
                case "16"://分支
                    break;
                case "17"://参数
                    break;
                case "18"://数据源
                    break;
                case "19"://外拨服务
                    break;
                case "21"://数据验证
                    break;
            }
            $this->jumpTo($NextStep);
            return $command;
        }catch (\Exception $e){
            return $e;
        }
    }

    /**
     * 满足条件就跳转到第几部
     * @param $tiaojian
     * @param $to
     * @param $command
     */
    public function judgeJump($tiaojian,$to){
        $this->comd .= "\t\t" . "if $tiaojian then" . "\r\n";
        $this->comd .= "\t\t\t" . "step".$to . "()\r\n";
        $this->comd .= "\t\t" . "end" . "\r\n";
    }
    /**
     * 跳转到第几部
     */
    public function jumpTo($to){
        if (count($to) == 1) {
            $this->comd .= "\t\t" . "step$to[0]()" . "\r\n";
        }
    }
    /**
     * 判断
     */
    public function judge($comd,$var=2){
        for ($i=0;$i<$var;$i++){
            $this->comd .= "\t";
        }
        $this->comd .= "if $comd then" . "\r\n";
    }
    /**
     * 跳转到第几部
     */
    public function add($comd,$var=2){
        for ($i=0;$i<$var;$i++){
            $this->comd .= "\t";
        }
        $this->comd .= "$comd" . "\r\n";
    }
    /**
     * 结束
     */
    public function end($var=2){
        for ($i=0;$i<$var;$i++){
            $this->comd .= "\t";
        }
        $this->comd .= "end" . "\r\n";
    }

    public function addMySql(){
        $this->add('require"luasql.mysql"',0);
        $this->add('env=luasql.mysql()',0);
        $this->add('conn=env:connect("crm","root","root","10.105.203.200",3306)',0);
        $this->add('conn:execute"SET NAMES GB2312"',0);
        $this->add('cur=conn:execute("select * from cti_jnz")',0);
        $this->add('row=cur:fetch({},"aaaa")',0);
        $this->add('while row do',0);
        $this->add('var=string.format("%d%s\n",row.id,row.name)',2);
        $this->add('print(var)',2);
        $this->add('row=cur:fetch(row,"aaaa")',2);
        $this->add('end',0);
        $this->add('conn:close()',0);
        $this->add('env:close()',0);
    }

    //过滤器，过滤空的
    public static function notEmpty($var)
    {
        return($var!="");
    }
    /**
     * 文件列表
     */
    public function actionFileList()
    {
        return $this->getFileList(new CtiFile(),"cti_ivr_tu");
    }





}